<?php

/**
 * @file
 * Contains \Drupal\gdlisnet\Plugin\QueueWorker\UpdatePhoto.
 */

namespace Drupal\gdlisnet\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;

/**
 * Updates a reader's photo.
 *
 * @QueueWorker(
 *   id = "gdlisnet_photo_exchange",
 *   title = @Translation("Reader\'s Photo Exchange"),
 *   cron = {"time" = 60}
 * )
 */
class UpdatePhoto extends QueueWorkerBase {

  /**
   * {@inheritdoc}
   */
  public function processItem($reader_info) {
	$reader=$reader_info->smt_salaryno;
	$photo=$reader_info->smt_photo;

	// First let's fetch all the database settings
	$gdlisnet_database = \Drupal::config('gdlisnet.datasource');
	
	try {
		// Use php-oci8 rather than pdo_oci to deal with blob data, which is faster
		$conn=oci_connect($gdlisnet_database->get('username'), $gdlisnet_database->get('password'),
			sprintf("%s:%s/%s", $gdlisnet_database->get('host'), $gdlisnet_database->get('port'), $gdlisnet_database->get('database')), 'AL32UTF8'
		);
		if(!$conn) {
			$e=oci_error();
			throw new \Exception($e['message']);
		}
		
		if(!empty($photo)) {
			// First let's empty the blob
			$sql=sprintf("UPDATE 读者库 SET 照片=EMPTY_BLOB() WHERE 读者条码='%s'", $reader);
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			oci_commit($conn);
			oci_free_statement($stmt);

			// Now let's fill the blob
			$sql=sprintf("SELECT * FROM 读者库 WHERE 读者条码='%s' FOR UPDATE", $reader);
			$stmt = oci_parse($conn, $sql);
			if(!$stmt) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$r=oci_execute($stmt, OCI_DEFAULT);
			if(!$r) {
				$e=oci_error($stmt);
				throw new \Exception($e['message']);
			}
			$row = oci_fetch_assoc($stmt);
			if($row) {
				$row['照片']->truncate();
				$row['照片']->save($photo);
				oci_commit($conn);
				\Drupal::logger('gdlisnet2smartibus')->info('Photo of @reader has been updated.',
					['@reader'=>$reader]
				);
			}
		}
	} catch (Exception $e) {
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
		throw new \Exception($e->getMessage());
	} finally {
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
	}
  }
}
?>
